package com.healthguide.backend.controller;

import com.healthguide.backend.entity.HealthRecord;
import com.healthguide.backend.repository.HealthRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/health-records")
@CrossOrigin(origins = "*")
public class HealthRecordController {
    
    @Autowired
    private HealthRecordRepository healthRecordRepository;
    
    @GetMapping("/user/{userId}")
    public List<HealthRecord> getUserHealthRecords(@PathVariable Long userId) {
        return healthRecordRepository.findByUserIdOrderByRecordDateDesc(userId);
    }
    
    @GetMapping("/user/{userId}/range")
    public List<HealthRecord> getHealthRecordsByRange(
            @PathVariable Long userId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        return healthRecordRepository.findByUserIdAndRecordDateBetween(userId, start, end);
    }
    
    @PostMapping
    public HealthRecord createHealthRecord(@RequestBody HealthRecord healthRecord) {
        return healthRecordRepository.save(healthRecord);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<HealthRecord> updateHealthRecord(
            @PathVariable Long id,
            @RequestBody HealthRecord healthRecordDetails) {
        return healthRecordRepository.findById(id)
                .map(healthRecord -> {
                    healthRecord.setWeight(healthRecordDetails.getWeight());
                    healthRecord.setSleepHours(healthRecordDetails.getSleepHours());
                    healthRecord.setWaterIntake(healthRecordDetails.getWaterIntake());
                    healthRecord.setExerciseMinutes(healthRecordDetails.getExerciseMinutes());
                    healthRecord.setMoodScore(healthRecordDetails.getMoodScore());
                    healthRecord.setNotes(healthRecordDetails.getNotes());
                    return ResponseEntity.ok(healthRecordRepository.save(healthRecord));
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteHealthRecord(@PathVariable Long id) {
        return healthRecordRepository.findById(id)
                .map(healthRecord -> {
                    healthRecordRepository.delete(healthRecord);
                    return ResponseEntity.ok().build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
}
